import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getMovieCategory, getCategory, createCategory, updateCategory, deleteCategory, getIdCategory, categoryStatusChange, createFile, updateFile, findFileById, deleteFileById, getMovieCountry, getMovieLanguageCon, getMovieCategoryByAdmin, getCountryByAdmin, deleteCountry, createCountry, updateCountry } from './category.service';
import { getFavorite } from '../favorites/favorites.service';
import { cornerDestroyById } from '../corner/common.service';
import { createNotice } from '../notification/notification.service';


// 获取电影类目
export const category = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {

  try {
    const data = await getMovieCategory();

    response.send(data);
  } catch (error) {
    console.log("error:: ", error);
  }
}

// 获取电影类目
export const categoryByAdmin = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  const { pageNo } = request.query;
  const { pageSize } = request.query;
  let status: any;
  
  if (parseInt(`${pageSize}`, 10) == 10) {
    status = 'status OR status IS NULL';
  } else {
    status = 1;
  }

  try {
    const data = await getMovieCategoryByAdmin(parseInt(`${pageNo}`, 10), parseInt(`${pageSize}`, 10), status);
    response.send(data);
  } catch (error) {
    next(error);;
  }
  
}

// 获取国家
export const countryByAdmin = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  const { pageNo } = request.query;
  const { pageSize } = request.query;

  try {
    const data = await getCountryByAdmin(parseInt(`${pageNo}`, 10), parseInt(`${pageSize}`, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
  
}

/**
 * 删除国家 (admin)
 */
export const destroyCountry = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteCountry(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error)
  }
}

/**
 * 创建国家
 */
export const addCountry = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let countryModal = request.body;

  if (countryModal.id && countryModal.id > 0) {
    const data = await updateCountry(countryModal, parseInt(countryModal.id, 10));
    response.send(data);
  } else {
    const data = await createCountry(countryModal);
    response.send(data);
  }

}







/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = request.query.status;

  const data = await getCategory(parseInt(`${status}`, 10));

  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const categoryDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdCategory(parseInt(postId, 10));

    const user = request.user;
    if (user && user.id > 0) {
      let favoriteParam = { user_id: user.id, type: 3, target_id: data.id }
      let favorite = await getFavorite(favoriteParam);
      data.favorite = (favorite as any).length > 0 ? favorite[0] : null;
    }

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let categoryModal = request.body;
  delete categoryModal.count;
  delete categoryModal.categoryLikeTotal;
  delete categoryModal.comment_total;

  if (categoryModal.id && categoryModal.id > 0) {
    const data = await updateCategory(categoryModal, parseInt(categoryModal.id, 10));
    response.send(data);
  } else {
    const data = await createCategory(categoryModal);
    response.send(data);
  }

}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 更新内容
  const post = _.pick(request.body, [
    'status',
    'attributes',
    'remark_zh',
    'remark_ug',
    'name_zh',
    'name_ug',
    'lectureRange_zh',
    'lectureRange_ug',
    'releaseTime',
    'price',
    'area',
    'unitType_zh',
    'unitType_ug',
    'buildTime',
    'floor',
    'processing_zh',
    'processing_ug',
    'detailed_zh',
    'detailed_ug',
    'contactPerson_zh',
    'contactPerson_ug',
    'weChat',
    'phoneNum'
  ]);

  // 更新内容
  try {
    const data = await updateCategory(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  // const { postId } = request.params;
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteCategory(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error)
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;

  // 获取内容
  const post = _.pick(request.body, ['status', 'remark_zh', 'remark_ug']);

  // 执行
  try {
    let house = await getIdCategory(postId);
    const data = await categoryStatusChange(parseInt(postId, 10), post);
    if (data) {
      let notice = {
        type: 2,
        target_id: postId,
        target_type: 3,
        content_ug: post.remark_ug,
        content_zh: post.remark_zh,
        status: 0
      }
      // await createNotification(notice, house.user_id)
    }
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = request.query.target_type;
    target_id = request.query.target_id;
  }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/category/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })
    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const houseData = await updateCategory(post as any, parseInt(`${target_id}`, 10));

    // 做出响应
    response.status(200).send(houseData)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 做出响应
    response.sendFile(file.filename, {
      root: 'uploads/category',
      headers: {
        'Content-Type': file.mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    result,
    status: 1,
    msg: 'ok'
  })

}
